<template>
  <div class="residence-reissue">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <!-- 申请人信息 -->
      <el-divider content-position="left">申请人信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="personIdCard">
            <el-input
              v-model="form.personIdCard"
              placeholder="请输入身份证号"
              maxlength="18"
              show-word-limit
              :loading="personLoading"
              @input="handleIdCardInput"
              @blur="handleIdCardBlur"
            >
              <template #suffix>
                <el-icon v-if="personLoading" class="is-loading"><Loading /></el-icon>
                <el-icon v-else-if="personInfo.name" color="#67c23a"><CircleCheck /></el-icon>
                <el-icon v-else-if="form.personIdCard && form.personIdCard.length === 18 && !validateIdCard(form.personIdCard)" color="#f56c6c"><CircleClose /></el-icon>
              </template>
            </el-input>
            <div v-if="personInfo.name" class="person-info-display">
              <el-tag type="primary" size="small">
                <el-icon><User /></el-icon>
                {{ personInfo.name }} ({{ formatGender(personInfo.gender) }})
              </el-tag>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="请输入联系电话"
              maxlength="11"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 补办信息 -->
      <el-divider content-position="left">补办信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="证件类型" prop="certificateType">
            <el-select v-model="form.certificateType" placeholder="请选择证件类型" style="width: 100%">
              <el-option label="居住证" value="3" />
              <el-option label="临时居住证" value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="补办原因" prop="reissueReason">
            <el-select v-model="form.reissueReason" placeholder="请选择补办原因" style="width: 100%" @change="handleReasonChange">
              <el-option label="遗失" value="lost" />
              <el-option label="损坏" value="damaged" />
              <el-option label="信息变更" value="change" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="详细说明" prop="applicationReason">
            <el-input
              v-model="form.applicationReason"
              type="textarea"
              :rows="4"
              :placeholder="reasonPlaceholder"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 遗失声明 -->
      <div v-if="form.reissueReason === 'lost'" class="lost-declaration">
        <el-divider content-position="left">遗失声明</el-divider>
        <el-alert
          title="重要提示"
          type="warning"
          :closable="false"
          show-icon
        >
          <p>居住证遗失后，原证件自动失效。如发现他人冒用，请及时报警。</p>
        </el-alert>
        
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-form-item label="遗失时间" prop="lostDate">
              <el-date-picker
                v-model="form.lostDate"
                type="date"
                placeholder="请选择遗失时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="遗失地点" prop="lostPlace">
              <el-input
                v-model="form.lostPlace"
                placeholder="请输入遗失地点"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="lostConfirm">
              <el-checkbox v-model="form.lostConfirm">
                我声明以上遗失情况属实，如有虚假，愿承担相应法律责任
              </el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 损坏说明 -->
      <div v-if="form.reissueReason === 'damaged'" class="damaged-info">
        <el-divider content-position="left">损坏说明</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="损坏程度" prop="damageLevel">
              <el-select v-model="form.damageLevel" placeholder="请选择损坏程度" style="width: 100%">
                <el-option label="轻微损坏" value="minor" />
                <el-option label="严重损坏" value="severe" />
                <el-option label="完全损坏" value="complete" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="损坏日期" prop="damageDate">
              <el-date-picker
                v-model="form.damageDate"
                type="date"
                placeholder="请选择损坏日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 信息变更 -->
      <div v-if="form.reissueReason === 'change'" class="change-info">
        <el-divider content-position="left">变更信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="变更类型" prop="changeType">
              <el-select v-model="form.changeType" placeholder="请选择变更类型" style="width: 100%">
                <el-option label="姓名变更" value="name" />
                <el-option label="居住地址变更" value="address" />
                <el-option label="工作单位变更" value="work" />
                <el-option label="其他信息变更" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变更日期" prop="changeDate">
              <el-date-picker
                v-model="form.changeDate"
                type="date"
                placeholder="请选择变更日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="2"
              placeholder="其他需要说明的信息（选填）"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          <el-icon><Check /></el-icon>
          提交补办申请
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 补办须知 -->
    <el-card class="notice-card" shadow="never">
      <template #header>
        <span>补办须知</span>
      </template>
      <div class="notice-content">
        <h4>补办条件：</h4>
        <ul>
          <li>居住证遗失、损坏或信息变更的</li>
          <li>原居住证仍在有效期内的</li>
          <li>居住地址未发生变化的</li>
        </ul>
        
        <h4>所需材料：</h4>
        <ul>
          <li>本人身份证及复印件</li>
          <li>本人近期免冠照片</li>
          <li>遗失声明（遗失补办）</li>
          <li>损坏的原证件（损坏补办）</li>
          <li>变更证明材料（信息变更）</li>
        </ul>
        
        <h4>办理时限：</h4>
        <ul>
          <li>材料齐全的，10个工作日内办结</li>
          <li>需要调查核实的，20个工作日内办结</li>
        </ul>
        
        <h4>注意事项：</h4>
        <ul>
          <li>补办期间可申请开具居住证明</li>
          <li>遗失补办需要重新缴费</li>
          <li>损坏补办根据损坏程度确定是否收费</li>
          <li>虚假申请将承担法律责任</li>
        </ul>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Check, 
  Loading, 
  CircleCheck, 
  CircleClose, 
  User 
} from '@element-plus/icons-vue'
import axios from 'axios'

// API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8088'

// 响应式数据
const loading = ref(false)
const personLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  personIdCard: '',
  phone: '',
  certificateType: '3',
  applicationType: '3', // 补领
  reissueReason: '',
  applicationReason: '',
  lostDate: '',
  lostPlace: '',
  lostConfirm: false,
  damageLevel: '',
  damageDate: '',
  changeType: '',
  changeDate: '',
  remark: ''
})

// 人员信息
const personInfo = ref({
  name: '',
  gender: null
})

// 根据补办原因生成占位符文本
const reasonPlaceholder = computed(() => {
  const placeholders = {
    'lost': '请详细说明居住证遗失的具体情况，包括遗失时间、地点、可能原因等',
    'damaged': '请详细说明居住证损坏的具体情况，包括损坏原因、损坏程度等',
    'change': '请详细说明需要变更的信息内容，包括变更原因、变更前后对比等',
    'other': '请详细说明补办原因和具体情况'
  }
  return placeholders[form.reissueReason] || '请详细说明补办原因'
})

// 表单验证规则
const rules = {
  personIdCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  certificateType: [
    { required: true, message: '请选择证件类型', trigger: 'change' }
  ],
  reissueReason: [
    { required: true, message: '请选择补办原因', trigger: 'change' }
  ],
  applicationReason: [
    { required: true, message: '请输入详细说明', trigger: 'blur' },
    { min: 10, message: '详细说明至少10个字符', trigger: 'blur' }
  ],
  lostDate: [
    { required: true, message: '请选择遗失时间', trigger: 'change' }
  ],
  lostPlace: [
    { required: true, message: '请输入遗失地点', trigger: 'blur' }
  ],
  lostConfirm: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请确认遗失声明'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  damageLevel: [
    { required: true, message: '请选择损坏程度', trigger: 'change' }
  ],
  damageDate: [
    { required: true, message: '请选择损坏日期', trigger: 'change' }
  ],
  changeType: [
    { required: true, message: '请选择变更类型', trigger: 'change' }
  ],
  changeDate: [
    { required: true, message: '请选择变更日期', trigger: 'change' }
  ]
}

// 身份证号输入处理
const handleIdCardInput = () => {
  personInfo.value = { name: '', gender: null }
}

// 身份证号失焦处理
const handleIdCardBlur = async () => {
  if (form.personIdCard && validateIdCard(form.personIdCard)) {
    await fetchPersonInfo()
  }
}

// 补办原因变化处理
const handleReasonChange = () => {
  // 清空相关字段
  form.applicationReason = ''
  if (form.reissueReason !== 'lost') {
    form.lostDate = ''
    form.lostPlace = ''
    form.lostConfirm = false
  }
  if (form.reissueReason !== 'damaged') {
    form.damageLevel = ''
    form.damageDate = ''
  }
  if (form.reissueReason !== 'change') {
    form.changeType = ''
    form.changeDate = ''
  }
}

// 验证身份证号格式
const validateIdCard = (idCard) => {
  const pattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  return pattern.test(idCard)
}

// 获取人员信息
const fetchPersonInfo = async () => {
  if (!form.personIdCard || !validateIdCard(form.personIdCard)) {
    return
  }

  personLoading.value = true
  
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    console.log('查询人员信息，身份证号:', form.personIdCard)

    const response = await axios.get(`${API_BASE_URL}/household/getPersonByIdCard`, {
      params: { idCard: form.personIdCard },
      headers: { 'token': token }
    })

    console.log('人员信息响应:', response.data)

    const result = response.data
    if (result.status === 200 && result.data) {
      personInfo.value = {
        name: result.data.name,
        gender: result.data.gender
      }
    } else {
      ElMessage.warning('未找到该身份证号对应的人员信息')
      personInfo.value = { name: '', gender: null }
    }

  } catch (error) {
    console.error('查询人员信息出错:', error)
    ElMessage.error('查询人员信息失败')
    personInfo.value = { name: '', gender: null }
  } finally {
    personLoading.value = false
  }
}

// 提交申请
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 验证人员信息是否已获取
    if (!personInfo.value.name) {
      ElMessage.error('请先输入有效的身份证号并确认人员信息')
      return
    }
    
    loading.value = true
    
    try {
      const token = localStorage.getItem('token')
      if (!token) {
        ElMessage.error('请先登录')
        return
      }

      // 构建提交数据
      const submitData = {
        personIdCard: form.personIdCard,
        certificateType: '居住证', // 固定为居住证类型
        applicationType: form.applicationType,
        applicationReason: '', // 补办原因
        remark: '' // 详细说明和备注
      }

      // 设置补办原因
      const reasonMap = {
        'lost': '证件遗失',
        'damaged': '证件损坏',
        'change': '信息变更',
        'other': '其他原因'
      }
      submitData.applicationReason = reasonMap[form.reissueReason] || '补领'

      // 构建详细说明和备注
      let remarkContent = form.applicationReason // 用户填写的详细说明
      remarkContent += `\n联系电话：${form.phone}`

      // 根据补办原因添加特殊信息
      if (form.reissueReason === 'lost') {
        remarkContent += `\n遗失时间：${form.lostDate}\n遗失地点：${form.lostPlace}\n遗失声明：已确认`
      } else if (form.reissueReason === 'damaged') {
        remarkContent += `\n损坏程度：${form.damageLevel}\n损坏日期：${form.damageDate}`
      } else if (form.reissueReason === 'change') {
        remarkContent += `\n变更类型：${form.changeType}\n变更日期：${form.changeDate}`
      }

      // 添加用户的其他备注
      if (form.remark) {
        remarkContent += `\n其他说明：${form.remark}`
      }

      submitData.remark = remarkContent

      console.log('提交居住证补办申请，数据:', submitData)
      
      // 调用后端接口提交申请
      const response = await axios.post(`${API_BASE_URL}/certificate/apply`, submitData, {
        headers: {
          'token': token,
          'Content-Type': 'application/json'
        }
      })
      
      console.log('居住证补办申请响应:', response.data)
      
      const result = response.data
      if (result.status === 200) {
        ElMessage.success(result.msg || '居住证补办申请提交成功')
        handleReset()
      } else {
        ElMessage.error(result.msg || '居住证补办申请提交失败')
      }
      
    } catch (error) {
      console.error('居住证补办申请提交出错:', error)
      
      if (error.response) {
        const errorMsg = error.response.data?.msg || '服务器错误，请稍后重试'
        ElMessage.error(errorMsg)
      } else if (error.request) {
        ElMessage.error('网络连接失败，请检查网络')
      } else {
        ElMessage.error('申请提交失败: ' + error.message)
      }
    } finally {
      loading.value = false
    }
  })
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  personInfo.value = { name: '', gender: null }
}

// 格式化性别显示
const formatGender = (gender) => {
  if (gender === 1) return '男'
  if (gender === 2) return '女'
  return '未知'
}
</script>

<style lang="scss" scoped>
.residence-reissue {
  .el-form {
    max-width: 800px;
  }

  .el-divider {
    margin: 20px 0;
  }

  .el-divider__text {
    font-weight: 600;
    color: #409eff;
  }

  .person-info-display {
    margin-top: 8px;
    
    .el-tag {
      font-size: 12px;
      padding: 4px 8px;
      border-radius: 4px;
      
      .el-icon {
        margin-right: 4px;
      }
    }
  }

  .lost-declaration, .damaged-info, .change-info {
    .el-alert {
      margin-bottom: 20px;
    }
  }

  .notice-card {
    margin-top: 30px;
    
    .notice-content {
      h4 {
        color: #303133;
        margin: 16px 0 8px 0;
        font-size: 14px;
        font-weight: 600;
      }
      
      ul {
        margin: 0 0 16px 0;
        padding-left: 20px;
        
        li {
          color: #606266;
          font-size: 14px;
          line-height: 1.6;
          margin-bottom: 4px;
        }
      }
    }
  }

  // 身份证号输入框加载状态
  .el-input {
    &.is-loading {
      .el-input__wrapper {
        .el-input__suffix {
          .el-icon.is-loading {
            animation: rotating 2s linear infinite;
          }
        }
      }
    }
  }

  @keyframes rotating {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .residence-reissue {
    .el-form {
      max-width: 100%;
    }
  }
}
</style>